﻿using Volo.Abp.Application.Services;
using MyBookStore.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories;
using MyBookStore.Domain;
using MyBookStore.Application.Model;

namespace MyBookStore.Application
{
    public class UserAppService : ApplicationService, IUserAppService
    {
        private readonly IRepository<Users> userRepository;
        private readonly MyBookStoreDbContext dbContext;
        public UserAppService(IRepository<Users> userRepository, MyBookStoreDbContext dbContext)
        {
            this.userRepository = userRepository;
            this.dbContext = dbContext;
        }

        protected IQueryable<Users> GetQueryable()
        {
            return this.dbContext.Set<Users>().AsQueryable();
        }

        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <returns></returns>
        public string GetUser()
        {
            return this.GetQueryable().FirstOrDefault()?.Name;
        }

        /// <summary>
        /// 校验用户登录
        /// </summary>
        /// <param name="no"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<Users> Login(string no, string password)
        {
            return await this.userRepository.GetAsync(u => u.No == no && u.Password == password);
            //return Task.Run(() => this.GetQueryable().FirstOrDefault(u => u.No == no && u.Password == password));
        }

        /// <summary>
        /// 校验用户登录
        /// </summary>
        /// <param name="no"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public UserDto Login2(string no, string password)
        {
            var user = this.GetQueryable().FirstOrDefault(u => u.No == no && u.Password == password);
            return ObjectMapper.Map<Users, UserDto>(user);
        }
    }
}
